<template>
  <el-row class="d-flex flex-column" v-if="$route.path === '/caption/finan'">
    <el-col :span="24">
      <form class="el-form query-form el-form--label-right el-form--inline">
        <div class="el-form-item el-form-item--medium" v-if="admin.mType == 2 || admin.mType == 3">
          <label for="name" class="el-form-item__label" style="width: 60px;">区</label>
          <div class="el-form-item__content">
            <div class="el-input el-input--medium">
              <el-select v-model="query.mRegion" placeholder="惠济区">
                <el-option label="惠济区" value="1349"></el-option>
              </el-select>
            </div>
            <!---->
          </div>
        </div>
        <div class="el-form-item el-form-item--medium" v-if="!(admin.mType >= 4)">
          <label for="date" class="el-form-item__label" style="width: 60px;">街道</label>
          <div class="el-form-item__content">
            <el-select
              v-model="query.mZhenid"
              clearable
              placeholder="请选择想要查看的街道"
              @change="get_villageAtt()"
            >
              <el-option
                v-for="(town, index) in townMes"
                :key="index"
                :label="town.zName"
                :value="town.zhenId"
              ></el-option>
            </el-select>
          </div>
          <!---->
        </div>
        <div class="el-form-item el-form-item--medium" v-if="!(admin.mType == 5)">
          <label for="date" class="el-form-item__label" style="width: 60px;">村</label>
          <div class="el-form-item__content">
            <el-select
              v-model="query.mVillageid"
              clearable
              placeholder="请选择想要查看的村"
              @change="get_groupAtt()"
            >
              <el-option
                v-for="(village, index) in villageAtt"
                :key="index"
                :label="village.vName"
                :value="village.villageId"
              ></el-option>
            </el-select>
          </div>
          <!---->
        </div>
        <div class="el-form-item el-form-item--medium">
          <label for="date" class="el-form-item__label" style="width: 60px;">组</label>
          <div class="el-form-item__content">
            <el-select v-model="query.zuId" clearable placeholder="请选择想要查看的组">
              <el-option
                v-for="(group, index) in groupAtt"
                :key="index"
                :label="group.zName"
                :value="group.zKey"
              ></el-option>
            </el-select>
          </div>
          <!---->
        </div>
        <div class="el-form-item el-form-item--medium ml-6">
          <!---->
          <div class="el-form-item__content">
            <el-button type="primary" icon="el-icon-search" @click="to_query">搜索</el-button>
            <!---->
          </div>
        </div>
        <div class="el-form-item el-form-item--medium ml-7" v-if="!(admin.mType == 3)">
          <div class="el-form-item__content">
            <el-button plain icon="el-icon-plus" @click="show_form">
              <span>添加</span>
            </el-button>
          </div>

          <!---->
        </div>
      </form>
    </el-col>
    <el-col :span="24">
      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(225, 225, 225, 0.8)"
        ref="multipleTable"
        :data="items"
        border
        tooltip-effect="dark"
        max-height="600"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="120" align="center"></el-table-column>
        <el-table-column type="index" width="120" align="center"></el-table-column>
        <el-table-column label="理财名称" width="240" align="center" prop="LC_name"></el-table-column>
        <el-table-column label="年份" width="200" align="center" prop="LC_year"></el-table-column>
        <el-table-column label="月份" width="200" align="center" prop="LC_month"></el-table-column>
        <el-table-column label="村" width="140" align="center" prop="V_Name"></el-table-column>
        <el-table-column label="编辑" align="center" show-overflow-tooltip>
          <template slot-scope="scope" v-if="$route.path === '/caption/finan'">
            <el-button type="primary" icon="el-icon-tickets">详情</el-button>
            <el-button
              v-if="!(admin.mType == 3)"
              type="danger"
              icon="el-icon-delete"
              @click="del(scope.$index, 'LC_name')"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-row>
          <el-col :span="12">
            <div
              class="grid-content bg-purple d-flex jc-between ai-center"
              v-if="!(admin.mType == 3)"
            >
              <el-button
                type="primary"
                icon="el-icon-delete"
                style="display: block;"
                class="h-1 w-1"
                @click="del_multip('LC_name')"
              ></el-button>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pagination.current_page"
                :page-sizes="pagination.page_sizes"
                :page-size="pagination.page_size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
              ></el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-col>
    <el-dialog
      title="新增资金理财"
      v-if="$route.path === '/caption/finan'"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :lock-scroll="true"
      :visible.sync="dialogFormVisible_create"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="5.625rem"
        class="d-flex flex-column w-10 p-2 pt-0"
      >
        <el-col :span="24">
          <el-col :span="24" class="d-flex flex-column">
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="name" class="el-form-item__label" style="width: 5.625rem;">区</label>
              <div class="el-form-item__content">
                <div class="el-input el-input--medium">
                  <el-select v-model="form.mRegion" disabled placeholder="惠济区">
                    <el-option label="惠济区" value="1349"></el-option>
                  </el-select>
                </div>
                <!---->
              </div>
            </div>
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">街道</label>
              <div class="el-form-item__content">
                <el-select
                  v-model="form.mZhenid"
                  clearable
                  :disabled="admin.mType >= 4"
                  placeholder="请选择想要查看的街道"
                  @change="get_villageAtt()"
                >
                  <el-option
                    v-for="(town, index) in townMes"
                    :key="index"
                    :label="town.zName"
                    :value="town.zhenId"
                  ></el-option>
                </el-select>
              </div>
              <!---->
            </div>
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">村</label>
              <div class="el-form-item__content">
                <el-select
                  v-model="form.mVillageid"
                  :disabled="admin.mType >= 5"
                  clearable
                  placeholder="请选择想要查看的村"
                  @change="get_groupAtt()"
                >
                  <el-option
                    v-for="(village, index) in villageAtt"
                    :key="index"
                    :label="village.vName"
                    :value="village.villageId"
                  ></el-option>
                </el-select>
              </div>
              <!---->
            </div>
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">组</label>
              <div class="el-form-item__content">
                <el-select v-model="form.LC_zu" clearable placeholder="请选择想要查看的组">
                  <el-option
                    v-for="(group, index) in groupAtt"
                    :key="index"
                    :label="group.zName"
                    :value="group.zKey"
                  ></el-option>
                </el-select>
              </div>
              <!---->
            </div>
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">名称</label>
              <div class="el-form-item__content">
                <el-input v-model="form.LC_name" clearable></el-input>
              </div>
            </div>
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">年份</label>
              <div class="el-form-item__content">
                <el-date-picker
                  v-model="form.LC_year"
                  type="year"
                  value-format="yyyy"
                  placeholder="选择年"
                ></el-date-picker>
              </div>
            </div>
            <div class="el-form-item el-form-item--medium mb-2 w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">月份</label>
              <div class="el-form-item__content">
                <el-date-picker
                  v-model="form.LC_month"
                  format="MM"
                  value-format="MM"
                  type="month"
                  placeholder="选择月"
                ></el-date-picker>
              </div>
            </div>

            <div class="el-form-item el-form-item--medium d-flex jc-start w-10 d-flex jc-start">
              <label for="date" class="el-form-item__label" style="width: 5.625rem;">图片上传</label>
              <div class="el-form-item__content flex-1">
                <el-upload
                  ref="upload"
                  :action="$http.defaults.baseURL + 'VInsert'"
                  list-type="picture-card"
                  :on-success="success_c"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :before-upload="set_form"
                  :on-change="file_change"
                  :auto-upload="false"
                  :data="form"
                  :multiple="true"
                  :http-request="uploadFile"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" size="tiny">
                  <img width="100%" :src="dialogImageUrl" alt />
                </el-dialog>
              </div>
            </div>
          </el-col>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="reset">重 置</el-button>
        <el-button type="primary" @click="create">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      //用户登录信息
      admin: {},
      //表格中的数据
      items: [
        //表格内容
      ],
      init_items: [
        //原始表格渲染数据
      ],
      loading: true,
      pagination: {
        current_page: 1,
        page_sizes: [20, 30, 50, 100],
        page_size: 20,
        total: 0,
        page_length: 0
      },
      dialogFormVisible_create: false,
      formLabelWidth: "100px",
      form: {
        //弹出框内容
      },
      query: {
        //检索对象
        method: true,
        data: {},
        mRegion: "1349"
      },

      init_items_mes: {
        count: 50
      },
      //序列id
      index_id: 0,
      index: 0,
      //对应镇
      townMes: [],
      //对应村
      villageAtt: [],
      //对应组
      groupAtt: [],
      //多删数组
      delAtt: [],
      multipleSelection: [],
      //文件上传
      fileList: [],
      file: {},
      formDate: "",

      //搜索功能
      query_items: [],
      //删除的对象
      del_obj: {},
      delMany: {},

      //create
      form: {
        src: []
      },
      formLabelWidth: "7.5rem",
      //upload
      dialogImageUrl: "",
      dialogVisible: false
    };
  },

  methods: {
    setQuery() {
      if (this.admin.mType == 4) {
        this.query.mRegion = this.admin.mRegion;
        this.query.mZhenid = this.admin.mZhenid;
        this.get_villageAtt();
      }
      if (this.admin.mType == 5) {
        this.query.mRegion = this.admin.mRegion;
        this.query.mZhenid = this.admin.mZhenid;
        this.query.mVillageid = this.admin.mVillageid;
        this.get_groupAtt();
      }
    },
    get_townMes(res) {
      res.region.forEach(item => {
        let obj = item.zhen;
        obj.village = item.village;
        this.townMes.push(obj);
      });
    },
    get_villageAtt() {
      this.townMes.forEach(item => {
        if (item.zhenId == this.query.mZhenid) {
          this.villageAtt = item.village;
        }
      });
    },
    setModel() {
      this.admin = this.$util.handleLocalStorage("get", "admin");
      let { mVillageid, mZhenid, mRegion, mType } = this.admin;
      this.model = { mVillageid, mZhenid, mRegion, mType };
      this.model.startPage = this.pagination.current_page;
      this.model.pageSize = this.pagination.page_size;
    },
    //请求数据
    async fetch() {
      this.setModel();
      const res = await this.$http.post(
        "/caiwu/findlicai",
        this.Qs.stringify(this.model)
      );
      this.get_townMes(res.data);
      this.items = res.data.data;
      this.init_items = res.data;
      this.up_pagination();
      this.loading = false;
      if (
        this.$util.getCookie("current_page") !== String(this.pagination.current_page)
      ) {
        this.handleCurrentChange(this.$util.getCookie("current_page"));
      }
      return res;
    },
    async get_groupAtt() {
      const res = await this.$http.get(
        `/caiwu/findZu/${this.query.mVillageid}`
      );
      this.groupAtt = res.data.data;
    },
    handleSelectionChange(val) {
      let att = [];
      this.multipleSelection = val;
      this.multipleSelection.forEach(item => {
        let { LC_Id } = item;
        att.push(LC_Id);
      });
      this.delAtt = att;
    },
    setIndex() {
      this.$basicMes.forEach((item, index) => {
        if (item.name == this.query.town) {
          this.villageAtt = this.$basicMes[index].village;
        }
      });
    },
    get_delObj() {
      let { managerId } = this.admin;
      this.del_obj = { managerId };
    },
    get_delMany() {
      let { managerId } = this.admin;
      this.delMany.LC_Id = this.delAtt;
      console.log(this.delMany);
    },
    del(index, name) {
      this.get_delObj();
      this.index_id = index;
      this.form = this.items[index];
      this.del_obj.LC_Id = this.form.LC_Id;
      this.$confirm(
        `此操作将永久删除 ${this.items[index][name]}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }
      )
        .then(async index => {
          const res = await this.$http.delete(`/caiwu/deleteLicai`, {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            data: this.Qs.stringify(this.del_obj)
          });
          console.log(".....////");
          console.log(res);
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.fetch();
          } else {
            this.$message({
              type: "error",
              message: "删除失败!"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    async del_multip(name) {
      if (!this.delAtt.length) {
        return;
      }
      this.get_delMany();
      let str = "";
      this.multipleSelection.forEach(item => {
        str += item[name] + "\t\t";
      });

      this.$confirm(`此操作将永久删除 ${str}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(async index => {
          console.log(".....////");
          const res = await this.$http.delete(
            `/caiwu/deleteManyLicai/${this.delAtt.toString()}/${
              this.admin.managerId
            }`
          );

          console.log(".....////");
          console.log(res);
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.fetch();
          } else {
            this.$message({
              type: "error",
              message: "删除失败!"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //分页功能
    up_pagination() {
      this.pagination.page_length = Math.ceil(
        this.init_items.count / this.pagination.current_page
      );
      this.pagination.total = this.init_items.count;
    },

    handleSizeChange(val) {
      this.pagination.page_size = val;
      this.pagination.current_page = 1;
      this.up_table();
    },
    async handleCurrentChange(val) {
      if (this.pagination.current_page != val) {
        this.pagination.current_page = val;
        this.$util.setCookie("current_page", this.pagination.current_page);
        if (this.pagination.method) {
          this.loading = true;
          this.setModel();
          const res = await this.$http.post(
            "/caiwu/findCapitaldetails",
            this.Qs.stringify(this.model),
            {
              headers: { "Content-Type": "application/x-www-form-urlencoded" }
            }
          );
          this.items = res.data.data;
          if (res.status == 200) {
            setTimeout(() => {
              this.loading = false;
            }, 600);
          }
        } else {
          this.up_table();
        }
      }
    },
    //query
    async to_query() {
      this.query.startPage = this.pagination.current_page;
      this.query.pageSize = this.pagination.page_size;
      const res = await this.$http.post(
        "/caiwu/findlicai",
        this.Qs.stringify(this.query)
      );
      this.items = res.data.data;
      this.init_items = res.data;
      this.up_pagination();
      this.loading = false;
      if (
        this.$util.getCookie("current_page") !== String(this.pagination.current_page)
      ) {
        this.handleCurrentChange(this.$util.getCookie("current_page"));
      }
    },

    //create
    reset() {
      this.$confirm("确定重置新增数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }).then(() => {
        this.$message({
          type: "success",
          message: "已重置"
        });
        this.form = {};
      });
    },
    cancel() {
      this.$confirm("取消添加将不会保存该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "已取消！"
          });
          this.form = {};
          this.dialogFormVisible_create = false;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },
    success(res, file, files) {
      if (res.status === 200) {
        this.$message({
          type: "success",
          message: "添加成功！"
        });
        this.fetch();
        this.dialogFormVisible_create = false;
      } else {
        this.$message({
          type: "success",
          message: "添加失败!"
        });
      }
    },
    handleRemove(file, files) {
      let att = [];
      files.forEach(item => {
        let { name, url } = item;
        att.push({ name, url });
      });
      this.form.src = att;
      console.log(this.form);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    show_init() {
      // this.form.area = '1349'
      switch (this.admin.mType) {
        case 2:
          // this.get_townAtt(true);
          break;
        case 3:
          break;
        case 4:
          // this.get_townAtt(true);
          this.form.mZhenid = this.admin.mZhenid;
          this.get_villageAtt(true);
          break;
        case 5:
          // this.get_townAtt(true);
          this.form.mZhenid = this.admin.mZhenid;
          this.get_villageAtt(true);
          this.form.mVillageid = this.admin.mVillageid;
          break;
      }
    },
    show_form() {
      this.show_init();
      this.dialogFormVisible_create = true;
    },
    file_change(file, fileList) {
      this.file = file.raw;
      this.fileList = fileList;
    },
    async uploadFile(files) {
      this.formDate.append("file", files.file);
    },
    async create() {
      this.form.managerId = this.admin.managerId;
      if (this.fileList.length > 0) {
        this.formDate = new FormData();
        this.$refs.upload.submit();
        for (let item in this.form) {
          this.formDate.append(item, this.form[item]);
        }
        const res = await this.$http.post("/caiwu/insertLicai", this.formDate);
        if (res.status === 200) {
          this.$message({
            type: "success",
            message: "添加成功！"
          });
          this.fetch();
          this.dialogFormVisible_create = false;
        } else {
          this.$message({
            type: "success",
            message: "添加失败!"
          });
        }
      } else {
        const res = await this.$http.post("/caiwu/insertLicai", this.form, {
          headers: { "Content-Type": "multipart/form-data" }
        });
        if (res.status === 200) {
          this.$message({
            type: "success",
            message: "添加成功！"
          });
          this.fetch();
          this.dialogFormVisible_create = false;
        } else {
          this.$message({
            type: "success",
            message: "添加失败!"
          });
        }
      }
    }
  },

  created() {
    this.admin = this.$util.handleLocalStorage("get", "admin");
    this.pagination.current_page = 1;
    this.$util.setCookie("current_page", this.pagination.current_page);
    this.setQuery();
    this.fetch();
  }
};
</script>

<style lang="scss" scoped>
.query-form {
  padding-top: 20px;
  margin-bottom: 20px;
  background-color: #f2f2f2;
  display: flex;
  justify-content: flex-start;
}
.el-form--inline .el-form-item {
  display: inline-block;
  margin-right: 10px;
  vertical-align: top;
}
</style>

